import { Injectable } from '@nestjs/common';
import { CreateTagManageDto } from './dto/create-tag-manage.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { resultUtil } from 'src/utils/result';
import * as dayjs from 'dayjs';


@Injectable()
export class TagManageService {
  constructor(private readonly prismaService: PrismaService) {}
  /**
   * 新增标签
  */
  async create(createTagManageDto: CreateTagManageDto) {
    const result  = await this.prismaService.tagManage.findFirst({
      where: {
        tagName: createTagManageDto.tagName
      }
    })
    if (result) {
      return resultUtil('标签存在', '000001')
    }
    await this.prismaService.tagManage.create({
      data: {
        ...createTagManageDto
      }
    })
    return resultUtil('', '000000')
  }
    /**
   * 获取标签列表
  */
  async query(queryInfo) {
    const { tagName, currentPage, pageSize } = queryInfo;
    const skip = (currentPage - 1) * pageSize;
    const where = {} as any;
    if (tagName) {
      where.tagName = { contains: tagName };
    }
    const [records, total] = await Promise.all([
      this.prismaService.tagManage.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          id: 'desc',
        },
      }),
      this.prismaService.tagManage.count({ where }),
    ]);
    return resultUtil('', '000000', {
      records: records?.map((item: any) => {
        let result = {
          ...item,
          createdAt: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
        }
        return result
      }),
      total: total,
    });
  }
  /**
 * 删除标签
 */
  async delete(id: number) {
    await this.prismaService.tagManage.delete({
      where: { id: +id },
    });
    return resultUtil('', '000000');
  }
  /**
   * 获取所有的标签
  */
 async getAll(){
  const result = await this.prismaService.tagManage.findMany()
  return resultUtil('', '000000', result)
 }
}
